import Joi from 'joi';
import Boom from '@hapi/boom';

import errorCodesBuilder from '../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('');

export default {
	tags: ['api', 'verification'],
	description: '认证文件下载',

	auth: {
		mode: 'required',
	},

	validate: {
		params: Joi.object({
			jobId: Joi.string().required(),
		}),
	},

	async handler(request, h) {
		const {
			params: { jobId },
			server: {
				app: {
					model: { Job },
				},
			},
		} = request;

		let job;
		try {
			job = await Job.findOne({ _id: jobId });
			if (!job) throw new Error(`认证文件下载 not found job ${jobId}`);
		} catch (err) {
			const error = errorCodes['[03]认证关联Job查询失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw Boom.serverUnavailable(error.rawMessage);
		}

		const challenge = job.verification.challenge;

		return h
			.response(challenge)
			.header('Content-Type', 'plain/text')
			.header('Content-Disposition', `attachment; filename=${challenge}.txt`);
	},
};
